/*
 * Copyright (C) 2007-2012 Geometer Plus <contact@geometerplus.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

package org.geometerplus.android.fbreader;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;

import com.example.administrator.fangbook.read.ReadActivity;

import org.geometerplus.fbreader.book.M17kPlainTxtBook;
import org.geometerplus.fbreader.fbreader.ActionCode;
import org.geometerplus.fbreader.fbreader.FBReaderApp;
import org.geometerplus.fbreader.fbreader.FBView;
import org.geometerplus.zlibrary.core.util.ZLColor;
import org.geometerplus.zlibrary.text.view.ZLTextSelection;
import org.geometerplus.zlibrary.text.view.ZLTextView;
import org.geometerplus.zlibrary.ui.android.view.animation.AnimationManager;

import java.sql.SQLException;

public class SelectionPopup extends ButtonsPopupPanel {
	public final static String ID = "SelectionPopup";

	public SelectionPopup(FBReaderApp fbReader) {
		super(fbReader);
	}

	@Override
	public String getId() {
		return ID;
	}

	View[] vs;

	@Override
	public void createControlPanel(ReadActivity activity, FrameLayout root)
	{
		if (myWindow != null && activity == myWindow.getActivity()) {
			return;
		}
		
		myWindow = new SelectionPopupWindow(activity, root,
				PopupWindow.Location.Floating, false);
		View view = LayoutInflater.from(activity).inflate(
				R.layout.read_note_edit_context_dialog_layout, null);
		vs = new View[] { view.findViewById(R.id.btn_underline_style1),
				view.findViewById(R.id.btn_underline_style2),
				view.findViewById(R.id.btn_underline_style3),
				view.findViewById(R.id.btn_underline_style4) };
		vs[0].setTag(new ZLColor(0xff9314));
		vs[1].setTag(new ZLColor(0x66d63a));
		vs[2].setTag(new ZLColor(0xfc5d4f));
		vs[3].setTag(new ZLColor(0x2655dd));
		view.findViewById(R.id.btn_underline).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				synchronized (AnimationManager.mLockObj)
				{
					// TODO Auto-generated method stub
					final FBReaderApp fbReader = (FBReaderApp) FBReaderApp
							.Instance();
					ZLTextSelection selection = fbReader.BookTextView.getEditSelection();
					if(fbReader != null && selection != null)
					{
						selection.setUnderLine(true);
						FBView fbView = (FBView) FBReaderApp.Instance()
								.getCurrentView();
						LocalDumpNote note = doAddOrUpdateUnderLine();
						if(note != null)
						{
							fbView.doAddNewNote(note);
							((FBView) FBReaderApp.Instance().getCurrentView()).clearSelection();
							Application.getViewWidget().repaintForcely();

						}



					}
				}

				hide();
			}
		});
		view.findViewById(R.id.btn_copy).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						final FBReaderApp fbReader = (FBReaderApp) FBReaderApp
								.Instance();
						fbReader.doAction(ActionCode.SELECTION_COPY_TO_CLIPBOARD);
						fbReader.doAction(ActionCode.SELECTION_HIDE_PANEL);
                        hide();
                    }
				});

		if (!CommonParams.USE_SHARE) {
			view.findViewById(R.id.btn_share).setVisibility(View.GONE);
			view.findViewById(R.id.read_note_edit_context_line).setVisibility(View.GONE);
		} else {
			view.findViewById(R.id.btn_share).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							final FBReaderApp fbReader = (FBReaderApp) FBReaderApp
									.Instance();
							fbReader.doAction(ActionCode.SELECTION_SHARE);
							fbReader.doAction(ActionCode.SELECTION_HIDE_PANEL);

						}
					});
		}

		view.findViewById(R.id.btn_note).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						FBReaderApp fbReader = (FBReaderApp) Application;
						ZLTextSelection selection = fbReader.BookTextView.getEditSelection();
						if(selection != null && fbReader.Model != null && fbReader.Model.Book != null && fbReader.Model.Book instanceof M17kPlainTxtBook){
							M17kPlainTxtBook book = (M17kPlainTxtBook) fbReader.Model.Book;
							Chapter readingChapter = book.getReader().getReadingChapter();
							if(readingChapter != null)
							{
								String bookId = book.getBookId();
								String bookName = book.getTitle();
								String chapterId = book.getReader().getReadingChapter().getId();
								String chapterName = book.getReader().getReadingChapter().getName();
								String chapterContent = fbReader.BookTextView.getSelectedText();
								fbReader.doAction(ActionCode.SELECTION_NOTE, bookId, bookName, chapterId, chapterName, chapterContent, selection);
								fbReader.doAction(ActionCode.SELECTION_HIDE_PANEL);

							}


							
						}

                        hide();
						
						
					}
				} );

		for (int i = 0; i < 4; i++) {
			View v = vs[i];
			v.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) 
				{
					for (View vv : vs) {
						vv.setSelected(vv == v);
					}
					if (mData != null) {
						mData.setStyleColor((ZLColor) v.getTag());
						mData.setUnderLine(true);

					}
					
					ssp.saveLastSelectPopUpColor((ZLColor) v.getTag());
					FBView fbView = (FBView) FBReaderApp.Instance()
							.getCurrentView();
					fbView.doAddNewNote(doAddOrUpdateUnderLine());
					((FBView) FBReaderApp.Instance().getCurrentView()).clearSelection();
					
					hide();
					
				}
			});
		}
		if(mData == null)
		{
			mData = ((FBView) FBReaderApp.Instance().getCurrentView()).getEditSelection();
		}
		reset();
		
		myWindow.addView(view);

		
		final FBReaderApp fbReader = (FBReaderApp) FBReaderApp.Instance();
		final ZLTextView txtView = fbReader.getTextView();
		move( txtView.getEditSelection(),  txtView.getSelectionStartY(),
				 txtView.getSelectionEndY());
		
		
	}

	private ZLTextSelection mData;

	public void move(ZLTextSelection data, int selectionStartY,
			int selectionEndY) {

		if (myWindow == null)
        {
			return;
		}

		mData = data;
		reset();

		
		final FBReaderApp fbReader = (FBReaderApp) FBReaderApp.Instance();
		final ZLTextView txtView = fbReader.getTextView();
		int startY = txtView.getSelectionStartY();
		int endY = txtView.getSelectionEndY();
		int screenHeight = GlobalApp.getInstance().getScreenHeight();
		LogUtil.d("ZLFile", "startY:" + startY + " endY:" + endY + " screenHeight:" + screenHeight);
		FrameLayout.LayoutParams p = (FrameLayout.LayoutParams) myWindow.getLayoutParams();
		int winHeight = myWindow.getMeasuredHeight();
		if(winHeight > 0)
		{
			if(startY - (20 + winHeight) >= 20)
			{
				p.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
				p.topMargin = startY - (20 + winHeight);
				p.bottomMargin = 0;
			}
			else if(endY + 20 + winHeight + 20 <= screenHeight)
			{
				p.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
				p.bottomMargin = 0;
				p.topMargin = endY + 20;
			}
			else
			{
				p.topMargin = 0;
				p.bottomMargin = 0;
				p.gravity = Gravity.CENTER;
			}
            myWindow.setLayoutParams(p);
		}


	}
	SystemSettings ssp = SystemSettings.getInstance();
	public void reset()
	{
		{
			ZLColor clr = ssp.getLastSelectPopUpColor();
			if(clr == null)
			{
				clr = (ZLColor) vs[0].getTag();
			}
			for (View v : vs) 
			{
				v.setSelected(clr.equals(v.getTag()));
				if(v.isSelected())
				{
					if(mData != null)
					{
						mData.setStyleColor((ZLColor) v.getTag());
						final FBReaderApp fbReader = (FBReaderApp) FBReaderApp
								.Instance();
                        fbReader.getViewWidget().repaintForcely();
                    }

                }
			}	
		}
		
	}
	private LocalDumpNote doAddOrUpdateUnderLine()
	{
		FBReaderApp fbReader = (FBReaderApp) Application;
		ZLTextSelection selection = fbReader.BookTextView.getEditSelection();
		if(selection != null && fbReader.Model != null && fbReader.Model.Book != null && fbReader.Model.Book instanceof M17kPlainTxtBook){
			M17kPlainTxtBook book = (M17kPlainTxtBook) fbReader.Model.Book;
			Chapter readingChapter = book.getReader().getReadingChapter();
			if(readingChapter != null)
			{
				String bookId = book.getBookId();
				String bookName = book.getTitle();
				String chapterId = book.getReader().getReadingChapter().getId();
				String chapterName = book.getReader().getReadingChapter().getName();
				String chapterContent = fbReader.BookTextView.getSelectedText();
				LocalDumpNote note = LocalDumpNote.createReadNodeData(bookId, bookName, chapterId, chapterName, chapterContent, selection);
				try {
					GlobalApp.getInstance().getDataHelper().getLocalUnderLineBlockseDao().createOrUpdate(note);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return note;
			}
			
		}
		return null;
		
	}
	protected void hide_()
	{
		super.hide_();
		LogUtil.d("ZLFile", "SelectionPopUp hide_()");
		FBReaderApp fbReader = (FBReaderApp) Application;
		//fbReader.BookTextView.clearSelection();
	}
	public void hide()
	{
		super.hide_();
		LogUtil.d("ZLFile", "SelectionPopUp hide()");
		
		FBReaderApp fbReader = (FBReaderApp) Application;
		//fbReader.BookTextView.clearSelection();
	}

	@Override
	public void doPreLayout() {
		
	}
}
